﻿using Autofac;
using Microsoft.Extensions.DependencyInjection;
using WeDonekRpc.Client;
using WeDonekRpc.Client.Ioc;

namespace WeDonekRpc.NetCoreModular
{
    public class IocServiceProviderFactory : IServiceProviderFactory<ContainerBuilder>
    {
        private readonly RpcStartBuilder _Buffer = null;
        private readonly IocBuffer _Ioc;
        public IocServiceProviderFactory ( Action<RpcStartBuilder> action ) : this()
        {
            action(this._Buffer);
        }
        public IocServiceProviderFactory ()
        {
            this._Buffer = RpcClient.CreateBuilder();
            this._Ioc = this._Buffer.Option.Ioc;
        }

        public ContainerBuilder CreateBuilder ( IServiceCollection services )
        {
            this._Buffer.Load();
            IocServiceProvider provider = new IocServiceProvider(RpcClient.Ioc);
            _ = this._Ioc.RegisterInstance<IServiceProvider>(provider);
            _ = this._Ioc.RegisterInstance<IServiceProviderIsService>(provider);
            _ = this._Ioc.RegisterInstance<IKeyedServiceProvider>(provider);
            _ = this._Ioc.RegisterInstance<ISupportRequiredService>(provider);
            _ = this._Ioc.RegisterInstance<IServiceScopeFactory>(new IocScopeFactory(RpcClient.Ioc));
            this._Ioc.AutoFacBuilder.Populate(services);
            return this._Ioc.AutoFacBuilder;
        }
        public IServiceProvider CreateServiceProvider ( ContainerBuilder builder )
        {
            this._Buffer.Build();
            return new IocServiceProvider(RpcClient.Ioc);
        }
    }
}
